import { requestTokenCreate, requestTokenRefresh, requestTokenRemove, requestGetCurrentUserInfo  } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  getUser,
  setUser,
  removeUser,
  getRefreshToken,
  setRefreshToken,
  removeRefreshToken,
} from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'

const getDefaultState = () => {
  const user = getUser() || {}
  return {
    token: getToken(),
    refreshToken: getRefreshToken(),
    name: user.name,
    avatar: user.avatar,
    roles: [],
    permissions: [],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_REFRESH_TOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  // user login
  LOGIN: async ({ commit, dispatch }, { account, password }) => {
    dispatch('RESET_TOKEN')

    let ret = {}

    try {
      const rsp = await requestTokenCreate({
        account,
        password,
      })

      console.log('LOGIN rsp', rsp)

      if (rsp.success) {
        const { auth_user, access_token, refresh_token, expires_in } = rsp
        setUser(auth_user, expires_in)
        setToken(access_token, expires_in)
        setRefreshToken(refresh_token, expires_in)

        commit('SET_TOKEN', access_token)
        commit('SET_REFRESH_TOKEN', refresh_token)
        ret = { success: true, message: '登录成功' }
      } else {
        ret = { success: false, message: rsp.message }
      }
    } catch (error) {
      console.log(error)
      ret = { success: false, message: '登录失败，请稍后重试' }
    }

    return ret
  },

  // 刷新登录信息
  REFRESH_TOKEN: async ({ commit }) => {
    try {
      const token = getRefreshToken()

      if (!token) {
        console.log('no refresh token available')
        return
      }

      const rsp = await requestTokenRefresh({ token })
      if (rsp.success) {
        const { access_token, refresh_token, expires_in } = rsp
        commit('SET_TOKEN', access_token)
        commit('SET_REFRESH_TOKEN', refresh_token)
        setToken(access_token, expires_in)
        setRefreshToken(refresh_token, expires_in)
      }
    } catch (error) {
      console.log(error)
    }
  },

  // get user info
  async getInfo({ commit, state }) {
    try {
      const { success, data, message } = await requestGetCurrentUserInfo()
      if(success) {
        const { user, roles, menus, permissions } = data

        // 用户必须要有相应的角色分配
        if (!roles || roles.length <= 0) {
          Message({
            message: '尚未分配权限，请联系管理员处理！',
            type: 'error',
            duration: 5 * 1000,
          })
          throw new Error('尚未分配角色的用户，无法登录')
        }

        commit('SET_ROLES', roles)
        commit('SET_PERMISSIONS', permissions)
        commit('SET_NAME', user.name)
        commit('SET_AVATAR', user.avatar)
        commit('permission/SET_REMOTE_ROUTES', menus, { root: true })

        return { roles }
      } else {
        throw new Error(message)
      }
    } catch (error) {
      console.log(error)
      throw error
    }
  },

  // user logout
  logout({ commit, state }) {
    try {
      requestTokenRemove()
    } catch (error) {
      console.log(error)
    }

    removeToken() // must remove  token  first
    removeRefreshToken()
    removeUser()
    resetRouter()
    commit('RESET_STATE')
  },

  // remove token
  RESET_TOKEN: ({ commit }) => {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      removeRefreshToken()
      removeUser()
      commit('RESET_STATE')
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
